package edu.ynu.se.xiecheng.achitectureclass.GreenHouse.Config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 配置拦截规则
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/login", "anon"); // 登录接口不需要认证
        filterChainDefinitionMap.put("/logout", "anon"); // 登出接口不需要认证
        filterChainDefinitionMap.put("/user/**", "anon"); // 用户相关接口需要认证
        filterChainDefinitionMap.put("/camera/**", "anon"); // 摄像头相关接口需要认证
        filterChainDefinitionMap.put("/device/**", "anon"); // 设备相关接口需要认证
        filterChainDefinitionMap.put("/greenhouse/**", "anon"); // 大棚相关接口需要认证
        // 允许 OPTIONS 请求
        filterChainDefinitionMap.put("/**", "anon[OPTIONS]");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm customRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(customRealm);

        // 配置 Session 管理器
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setGlobalSessionTimeout(1800000); // Session 过期时间（30分钟）
        securityManager.setSessionManager(sessionManager);

        return securityManager;
    }

    @Bean
    public CustomRealm customRealm() {
        return new CustomRealm();
    }
}